#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: 
@time: 2024/3/2 11:16 AM
@Function: 请输入模块功能描述
"""
import os
import time
from pathlib import Path

import allure
import pytest

from allure_commons.types import AttachmentType

from playwright.sync_api import Page, sync_playwright
from slugify import slugify

from pages.login_page.login_page import LoginPage

#
output_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "screenshots")


#
#
# @pytest.fixture(scope = 'session')
# def login_session(pytestconfig):  # 这里后续尝试传入：playwright:Playwright
#     print('前置登录执行-->')
#     playwright = sync_playwright().start()
#     browser = playwright.chromium.launch(headless = False, slow_mo = 2000)  # 这里的slow_mo就是让浏览器缓慢多少ms执行
#     context = browser.new_context(viewport = {'width': 1920, 'height': 1080})
#     page = context.new_page()
#     login_page = LoginPage(page)
#     login_page.navigate("test")
#     login_page.fill_username('18516700020')
#     login_page.fill_password('qhdia111')
#     login_page.click_login_button()
#     # 保存storage到指定的文件
#     storage_path = pytestconfig.rootpath.joinpath("auth/xbase.json")
#     context.storage_state(path = storage_path)
#     yield page
#     print('用例执行结束')
#     context.close()
#     browser.close()

# 如果使用这个夹具，结果只是调用同一个浏览器
@pytest.fixture(scope = "session")
def set_up_tear_down(browser):
    context = browser.new_context(viewport = {'width': 1920, 'height': 1080})
    page = context.new_page()
    page.goto('https://xbasetest.dxbim.com:18899/user/login')
    yield page


# 如果使用这个夹具，结果每个用例都会调用一次浏览器
@pytest.fixture()
def set_up_tear_down_no_login(page):
    page.goto('https://xbasetest.dxbim.com:18899/user/login')
    yield page


# 基于上面要编写上下文
@pytest.fixture(scope = 'session')
def create_browser_context(playwright):
    browser = playwright.chromium.launch(headless = False)  # --start-maximized
    context = browser.new_context(viewport = {'width': 1920, 'height': 1080})
    page = context.new_page()
    page.goto('https://xbasetest.dxbim.com:18899/user/login')
    page.locator("//*[@id=\"login_userName\"]").fill("18516700020")
    page.locator("//*[@id=\"login_password\"]").fill("qhdia111")
    page.locator("//button[@type=\"submit\"]").click()
    time.sleep(2)
    # login_page = LoginPage(page)
    # login_page.navigate("test")
    # login_page.fill_username('18516700021')
    # login_page.fill_password('qhdia111')
    # login_page.click_login_button()
    context.storage_state(path = "./auth/xbase.json")
    # time.sleep(5)
    yield context


# 下面这种方式与上面的区别是，可以放大浏览器，不需要手动设置浏览器尺寸，但是带来的问题是其余的用例在使用新的窗口
# @pytest.fixture(scope = 'session')
# def create_browser_context_new(playwright):
#     user_data_path = os.system(
#         'osascript -e \'tell application "System Events" to get POSIX path of (path to application "Chromium")\'')
#     print(">>>>>>", type(user_data_path))
#     context = playwright.chromium.launch_persistent_context(str(user_data_path), headless = False, channel = "chromium",
#                                                             args = ['--start-maximized'], no_viewport = True)
#     page = context.new_page()
#     page.goto('https://xbasetest.dxbim.com:18899/user/login')
#     page.locator("//*[@id=\"login_userName\"]").fill("18516700021")
#     page.locator("//*[@id=\"login_password\"]").fill("qhdia111")
#     page.locator("//button[@type=\"submit\"]").click()
#     time.sleep(2)
#     context.storage_state(path = "./auth/xbase.json")
#     yield context


# 这里配合上面的create_browser_context，可以不用重复登录，使用同一个上下文，这里如果使用需要去掉上面的context.storage_state这句
@pytest.fixture()
def set_up_tear_down_new1(create_browser_context):
    context = create_browser_context
    page = context.new_page()
    page.goto('https://xbasetest.dxbim.com:18899/update-logs')
    page.pause()
    yield page


# 这里配合上面的create_browser_context，由于新增了登录信息json文件，所以和下面结合可以读取认证authjson文件。这里如果使用需要加上上面的context.storage_state这句
@pytest.fixture()
def set_up_tear_down_new(create_browser_context, browser):
    context = browser.new_context(storage_state = "/Users/fengjiahui/gitee_project/playwright_auto/auth/xbase.json",
                                  viewport = {'width': 1920, 'height': 1080})
    page = context.new_page()
    page.goto('https://xbasetest.dxbim.com:18899/update-logs')
    yield page
    context.close()


@pytest.hookimpl(tryfirst = True, hookwrapper = True)
def pytest_runtest_makereport(item, call):
    pytest_html = item.config.pluginmanager.getplugin("html")
    # 获取钩子方法的调用结果
    outcome = yield
    screen_file = ""
    report = outcome.get_result()
    extra = getattr(report, "extra", [])
    if report.failed and "login_session" in item.funcargs:
        page = item.funcargs["login_session"]
        screenshot_name = time.strftime("%Y%m%d_%H%M%S") + ".png"
        screenshot_path = output_dir + "/" + screenshot_name
        # 将截图添加到 Allure 报告中
        with allure.step("失败截图："):
            allure.attach(page.screenshot(path = screenshot_path), name = "测试用例执行失败截图",
                          attachment_type = AttachmentType.PNG)
    # if report.when == "call":
    #     xfail = hasattr(report, "wasxfail")
    #     if report.failed or xfail and "create_browser_context" in item.funcargs:
    #         page = item.funcargs["create_browser_context"]
    #         screenshot_dir = Path("screenshots")
    #         screenshot_dir.mkdir(exist_ok = True)
    #         print("------->>>>>>>>",screenshot_dir)
    #         screen_file = str(screen_file+"/"+f"{slugify(item.nodeid)}.png")
    #         page.screenshot(path = screen_file)
    #
    #     if (report.skipped and xfail) or (report.failed and not xfail):
    #         extra.append(pytest_html.extras.png(screen_file))
    #     report.extra = extra
